import React, { useEffect, useState } from 'react';
import { Button, message, Popconfirm, Space, Table, Row, Col, Modal, Form, Input, DatePicker, Select,Checkbox,Upload } from 'antd';
import '../components.css';
import ExpenseService from '../../services/ExpenseService';
import { DeleteOutlined, UpCircleOutlined, PlusOutlined, SearchOutlined, SyncOutlined,UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import moment from 'moment';
import AddExpense from './AddExpense';

const { RangePicker } = DatePicker;
const { Option } = Select;

export default function ExpenseManagement() {
  const [expenses, setExpenses] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); 
  const [selectAll, setSelectAll] = useState(false); 
  const [expenseDetail, setExpenseDetail] = useState(null); // 存储当前选中的费用详情
  const [detailModalVisible, setDetailModalVisible] = useState(false); // 控制详情弹窗
  const [detailTime, setDetailTime] = useState(null); // 存储弹窗打开时的时间
  const [importLoading, setImportLoading] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false); // 新增状态，用于区分是添加还是编辑
  const [currentRecord, setCurrentRecord] = useState(null); // 存储当前编辑的记录
  const [sortConfig, setSortConfig] = useState({ key: 'expenseid', // 默认按费用编号排序direction: 'ascending', // 默认升序
  });
  // 点击详情按钮时调用
  const handleShowDetail = (record) => {
    setExpenseDetail(record); // 存储详情数据
    setDetailTime(moment());
    setDetailModalVisible(true); // 显示弹窗
  };
// 添加排序处理函数
const handleSort = () => {
  setSortConfig(prevConfig => ({
    key: 'expenseid', // 固定按费用编号排序
    direction: prevConfig.direction === 'ascending' ? 'descending' : 'ascending',
  }));
};
  const getAllExpenses = (params = {}) => {
    setLoading(true);
    ExpenseService.getAllExpenses(params).then((response) => {
      setExpenses(response.data);
      setLoading(false);
    }).catch(error => {
      console.log(error);
      setLoading(false);
    });
  };

  // 导入处理函数
  const handleImport = (info) => {
    setImportLoading(true);
    
    ExpenseService.importExpenses(info.file)
      .then(response => {
        if (response.data === "导入成功") {
          message.success('导入成功！');
          getAllExpenses();
        } else {
          message.error('导入失败: ' + response.data);
        }
      })
      .catch(error => {
        message.error('导入失败: ' + (error.response?.data || error.message));
      })
      .finally(() => {
        setImportLoading(false);
      });
  };

  // 修改导出处理函数
  const handleExport = () => {
    const params = form.getFieldsValue();
    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([_, v]) => v !== undefined && v !== '')
    );
    
    ExpenseService.exportExpenses(filteredParams)
      .then(response => {
        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `expenses_${moment().format('YYYYMMDDHHmmss')}.csv`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        message.success('导出成功！');
      })
      .catch(error => {
        message.error('导出失败: ' + (error.response?.data || error.message));
      });
  };

  useEffect(() => {
    getAllExpenses();
  }, []);

  // 处理单个行的选择变化
  const onSelectChange = (selectedKeys) => {
    setSelectedRowKeys(selectedKeys);
    setSelectAll(selectedKeys.length === expenses.length && expenses.length > 0);
  };

  // 全选/取消全选
  const handleSelectAll = () => {
    if (selectAll) {
      setSelectedRowKeys([]);
    } else {
      setSelectedRowKeys(expenses.map(expense => expense.id));
    }
    setSelectAll(!selectAll);
  };

  // 反选
  const handleInvertSelection = () => {
    const invertedSelection = expenses
      .map(expense => expense.id)
      .filter(id => !selectedRowKeys.includes(id));
    setSelectedRowKeys(invertedSelection);
    setSelectAll(false);
  };

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请至少选择一项');
      return;
    }
    
    message.success('删除成功!');
    Promise.all(selectedRowKeys.map(id => ExpenseService.deleteExpense(id)))
      .then(() => {
        getAllExpenses();
        setSelectedRowKeys([]);
        setSelectAll(false);
      })
      .catch(error => {
        console.log(error);
      });
  };

  const deleteExpense = (e) => {
    console.log(e);
    message.success('删除成功!');
    setTimeout(() => {
      ExpenseService.deleteExpense(e).then(response => {
        getAllExpenses();
      }).catch(error => {
        console.log(error);
      });
    }, 500);
  };

  const cancel = (e) => {
    console.log(e);
    message.error('删除失败!');
  };

  const showModal = () => {
    setIsModalVisible(true);
    setIsEditMode(false); // 设置为添加模式
    setCurrentRecord(null); // 清空当前记录
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const handleAddSuccess = () => {
    setIsModalVisible(false);
    getAllExpenses();
  };

  const handleAdd = () => {
    setIsModalVisible(true);
    setIsEditMode(false); // 设置为添加模式
    setCurrentRecord(null); // 清空当前记录
  };

  const onFinish = (values) => {
    const params = {
      expenseName: values.expenseName,
      expenseType: values.expenseType,
      expenseDate: values.expenseDate ? values.expenseDate.toDate() : undefined,
      supportName: values.supportName,
      expenseState: values.expenseState
    };
    
    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([_, v]) => v !== undefined && v !== '')
    );
    console.log("查询参数:", filteredParams);
    getAllExpenses(filteredParams);
  };

  const onReset = () => {
    form.resetFields();
    getAllExpenses();
  };

const handleEditRecord = () => {
  if (!expenseDetail) return;
  
  // 直接从expenseDetail获取数据，确保id正确
  setCurrentRecord({
    id: expenseDetail.key,  // 使用key作为id
    expenseName: expenseDetail.expensename,
    relatedCustomer: expenseDetail.relatedcustomer,
    expensePrice: expenseDetail.expenseprice,
    expenseType: expenseDetail.expensetype,
    expenseDate: expenseDetail.expensedate ? moment(expenseDetail.expensedate) : null,
    expenseState: expenseDetail.expensestate,
    supportName: expenseDetail.supportname
  });
  
  setIsEditMode(true);
  setIsModalVisible(true);
  setDetailModalVisible(false);
};

  // 处理删除记录
  // 处理删除记录
const handleDeleteRecord = () => {
  if (!expenseDetail) return;
  
  Modal.confirm({
    title: '确定删除这条记录吗?',
    content: '删除后将无法恢复',
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    onOk: () => {
      ExpenseService.deleteExpense(expenseDetail.key)
        .then(() => {
          message.success('删除成功!');
          getAllExpenses();
          setDetailModalVisible(false);
        })
        .catch(error => {
          console.log(error);
          message.error('删除失败!');
        });
    },
    onCancel: () => {
      message.info('已取消删除');
    },
  });
};

  const columns = [
    {
      title: '选择',
      key: 'selection',
      align: 'center',
      width: 60,
      render: (_, record) => (
        <input
          type="checkbox"
          checked={selectedRowKeys.includes(record.key)}
          onChange={() => {
            const newSelectedRowKeys = selectedRowKeys.includes(record.key)
              ? selectedRowKeys.filter(key => key !== record.key)
              : [...selectedRowKeys, record.key];
            onSelectChange(newSelectedRowKeys);
          }}
        />
      ),
    },
    {
      title: '费用编号',
      key: "expenseid",
      dataIndex: 'expenseid',
      align: 'center',
    },
    {
      title: '费用名称',
      key: "expensename",
      dataIndex: 'expensename',
      align: 'center',
    },
    {
      title: '关联客户',
      key: "relatedcustomer",
      dataIndex: 'relatedcustomer',
      align: 'center',
    },
    {
      title: '费用金额',
      key: "expenseprice",
      dataIndex: 'expenseprice',
      align: 'center',
    },
    {
      title: '费用类型',
      dataIndex: 'expensetype',
      key: "expensetype",
      align: 'center',
    },
    {
      title: '发生时间',
      dataIndex: 'expensedate',
      key: "expensedate",
      align: 'center',
    },
    {
      title: '报销状态',
      dataIndex: 'expensestate',
      key: "expensestate",
      align: 'center',
    },
    {
      title: '负责人员',
      dataIndex: 'supportname',
      key: "supportname",
      align: 'center',
    },
    {
      title: '操作',
      key: 'actions',
      align: 'center',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<UpCircleOutlined />}
            onClick={() => handleShowDetail(record)}
          >
            详情
          </Button>
          <Popconfirm
            title="确定删除?"
            onConfirm={() => deleteExpense(record.key)}
            onCancel={cancel}
            okText="是"
            cancelText="否"
          >
            <Button type='danger' icon={<DeleteOutlined />}>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const data = React.useMemo(() => {
  const sortedExpenses = [...expenses].sort((a, b) => {
    if (a.id < b.id) {
      return sortConfig.direction === 'ascending' ? -1 : 1;
    }
    if (a.id > b.id) {
      return sortConfig.direction === 'ascending' ? 1 : -1;
    }
    return 0;
  });

  return sortedExpenses.map((expense) => ({
    key: expense.id,
    expenseid: expense.id,
    expensename: expense.expenseName,
    relatedcustomer: expense.relatedCustomer,
    expenseprice: expense.expensePrice,
    expensetype: expense.expenseType,
    expensedate: expense.expenseDate ? moment(expense.expenseDate).format('YYYY-MM-DD') : '',
    expensestate: expense.expenseState,
    supportname: expense.supportName,
  }));
}, [expenses, sortConfig]);

  return (
    <div className='emplst'>
      <div className="title">全部费用</div>
      
      {/* Search Form */}
      <Form
        form={form}
        layout="inline"
        onFinish={onFinish}
        style={{
          marginBottom: 20,
          background: '#fafafa',
          padding: 20,
          borderRadius: 4,
          display: 'flex',
          alignItems: 'center'
        }}
      >
        <div style={{ flex: 1, display: 'flex', gap: 16 }}>
          <Form.Item name="expenseName" style={{ flex: 1 }}>
            <Input placeholder="搜索关键词" />
          </Form.Item>
          <Form.Item name="expenseType" style={{ flex: 1 }}>
            <Select placeholder="费用类型" style={{ width: '100%' }}>
              <Option value="招待费">差旅费</Option>
              <Option value="办公费">办公费</Option>
            </Select>
          </Form.Item>

          <Form.Item name="expenseDate" style={{ flex: 1 }}>
            <DatePicker style={{ width: '100%' }} placeholder="发生时间" format="YYYY-MM-DD" />
          </Form.Item>

          <Form.Item name="supportName" style={{ flex: 1 }}>
            <Input placeholder="负责人员" />
          </Form.Item>

          <Form.Item name="expenseState" style={{ flex: 1 }}>
            <Select placeholder="报销状态" style={{ width: '100%' }}>
              <Option value="未报销">未报销</Option>
              <Option value="已报销">已报销</Option>
            </Select>
          </Form.Item>
        </div>
        
        <Form.Item style={{ marginLeft: 'auto' }}>
          <Space>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
            <Button onClick={onReset} icon={<SyncOutlined />}>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>

      <Row justify="space-between" style={{ marginBottom: 16 }}>
        <Col>
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAdd}
            >
              添加
            </Button>
            {/* 导入按钮 */}
            <Upload
              accept=".csv"
              showUploadList={false}
              customRequest={handleImport}
              beforeUpload={(file) => {
                const isCsv = file.type === 'text/csv' || file.name.endsWith('.csv');
                if (!isCsv) {
                  message.error('只能上传CSV文件!');
                }
                return isCsv;
              }}
            >
              <Button
                type="primary"
                icon={<UploadOutlined />}
                loading={importLoading}
              >
                导入
              </Button>
            </Upload>
            
            {/* 导出按钮 */}
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              onClick={handleExport}
            >
              导出
            </Button>
            
          </Space>
        </Col>
        <Col>
          <Space>
    {/*修改排序按钮部分*/}
<Button
  type="primary"
  icon={<UpCircleOutlined />}
  onClick={handleSort}
>
  {sortConfig.direction === 'ascending' ? '排序' : '排序'}
</Button>
            <Button
              type="primary"
              icon={<UpCircleOutlined />}
            >
              列表
            </Button>
          </Space>
        </Col>
      </Row>

      <Modal
        title="费用详情"
        visible={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="delete" danger onClick={handleDeleteRecord}>
            删除记录
          </Button>,
          <Button key="edit" type="default" onClick={handleEditRecord}>
            编辑记录
          </Button>,
          <Button key="close" type="primary" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>,
        ]}
        width={800}
      >
        {expenseDetail && (
          <div>
            <div style={{ marginBottom: 16 }}>
              基本信息
            </div>
            
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <tbody>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>费用编号：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{expenseDetail.expenseid}</td>
                </tr>
                <tr>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>费用名称：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{expenseDetail.expensename}</td>
                </tr>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>费用金额：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{expenseDetail.expenseprice}</td>
                </tr>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>费用类型：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{expenseDetail.expensetype}</td>
                </tr>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>发生时间：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{expenseDetail.expensedate}</td>
                </tr>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>关联客户：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{expenseDetail.relatedcustomer}</td>
                </tr>
                <tr>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>报销状态：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{expenseDetail.expensestate}</td>
                </tr>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>负责人员：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{expenseDetail.supportname}</td>
                </tr>
              </tbody>
            </table>

            <div style={{ marginBottom: 16 }}>
              系统信息
            </div>
            
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <tbody>
                <tr>
                  <td style={{ width: '30%', padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>录入人员：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{expenseDetail.supportname}</td>
                </tr>
                <tr>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>创建时间：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>{expenseDetail.expensename}</td>
                </tr>
                <tr>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0', background: '#fafafa' }}>当前时间：</td>
                  <td style={{ padding: '8px', border: '1px solid #f0f0f0' }}>
                    {detailTime ? detailTime.format('YYYY-MM-DD HH:mm:ss') : '--'}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        )}
      </Modal>

     <Modal
  title={isEditMode ? "编辑费用" : "添加费用"}
  visible={isModalVisible}
  onCancel={handleCancel}
  footer={null}
  width={800}
  destroyOnClose
>
  <AddExpense 
    onSuccess={() => {
      handleAddSuccess(); // 这会关闭弹窗并刷新列表
      if (isEditMode) {
        setDetailModalVisible(false); // 如果是编辑模式，也关闭详情弹窗
      }
    }}
    isEditMode={isEditMode} 
    record={currentRecord}
  />
</Modal>

      <Table 
        columns={columns} 
        dataSource={data} 
        bordered={true} 
        loading={loading}
      />
      <Button
        type="primary"
        onClick={handleSelectAll}
      >
        {selectAll ? '取消全选' : '全选'}
      </Button>
      <Button
        type="primary"
        onClick={handleInvertSelection}
      >
        反选
      </Button>
      <Button
        type="primary"
        icon={<DeleteOutlined />}
        onClick={handleBatchDelete}
        danger
      >
        批量删除
      </Button>
    </div>
  );
}